package com.csp.session.impl;

import com.csp.session.ConnectionFactory;
import com.csp.util.DBUtil;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.logging.Logger;

/**
 * 相当于连接池
 * @author:chengsp
 * @createTime:2019/8/22 13:35
 */
public class ConnectionFactoryImpl implements ConnectionFactory {
    private Queue<Connection> activeConnQueue = new ConcurrentLinkedDeque<>();
    private Queue<Connection> usingConnQueue = new ConcurrentLinkedDeque<>();

    public ConnectionFactoryImpl() {
        init();
    }

    private void init() {
        for (int i = 0; i < 5; i++) {
            activeConnQueue.offer(DBUtil.getConnection());
        }
    }

    @Override
    public Connection getConnection() {
        Connection connection = activeConnQueue.poll();
        usingConnQueue.offer(connection);
        return connection;
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public void revertConnection(Connection connection) {
        activeConnQueue.offer(connection);
        usingConnQueue.remove(connection);
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
